﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Security.Claims;
using Zhao.Arena.Utility.InitDatabaseExt;
using Zhao.Common.EnumEntity;
using Zhao.Common.Helper;
using Zhao.IServer.Events;
using Zhao.IServer.Field;
using Zhao.IServer.Management_Arena;
using Zhao.Models.DTO;
using Zhao.Models.Entity;

namespace Zhao.Arena.Controllers.ActivityManagement
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class ActivitiesController : ControllerBase
    {
        private readonly IVenuesServer _venuesServer;
        private readonly IActivitiesServer _activitiesServer;
        private readonly IFieldTypesServer _fieldTypesServer;
        private readonly IActivityMembersServer _activityMembersServer;

        public ActivitiesController(IVenuesServer venuesServer, IActivitiesServer activitiesServer, IActivityMembersServer activityMembersServer)
        {
            this._venuesServer = venuesServer;
            this._activitiesServer = activitiesServer;
            this._activityMembersServer = activityMembersServer;
        }

        [HttpGet]
        [Route("{pageIndex:int}/{pageSize:int}")]
        [Route("{pageIndex:int}/{pageSize:int}/{searchaString}")]
        [Route("{pageIndex:int}/{pageSize:int}/{searchaString}/{displayDate}")]
        public async Task<JsonResult> GetPage(int pageIndex, int pageSize, string searchaString = "", string displayDate = "")
        {
            var result = new ApiResult<PageModel<ActivitiesDTO>>() { Success = false, Message = "操作失败" };

            string? venueIdClaim = User.FindFirst("VenueId").Value;

            Guid.TryParse(venueIdClaim, out Guid venueId);

            Expressionable<Activities, Venues, FieldTypes> expressionable = new Expressionable<Activities, Venues, FieldTypes>();

            //模糊查询
            expressionable.AndIF(!searchaString.IsNullOrWhiteSpace(), (a, b, c) => a.Title.Contains(searchaString) || a.Description.Contains(searchaString));

            expressionable.OrIF(searchaString.IsValidIsoDate(), (a, b, c) => a.DisplayDate.Equals(searchaString));

            //确保日期格式的正确性
            expressionable.AndIF(!displayDate.IsNullOrWhiteSpace() && displayDate.IsValidIsoDate(), (a, b, c) => a.DisplayDate.Equals(displayDate));

            //如果是球馆管理员就展示当前球馆的活动就行
            expressionable.AndIF(venueId!=default, (a, b, c) => a.VenueID.Equals(venueId));

            result.Data = await _activitiesServer.ActivitiQueryPageModel(expressionable.ToExpression(), pageIndex, pageSize);

            if (result.Data != null)
            {
                result.Success = true;
                result.Message = "操作成功";
            }

            return new JsonResult(result);
        }


        /// <summary>
        /// 添加活动
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> AddActivity([FromBody] ActivitiesDTO dto)
        {
            var result = new ApiResult
            {
                Success = false
            };

            // 验证必填字段
            if (dto.Title.IsNullOrWhiteSpace())
            {
                result.Message = "活动标题不能为空";
                return new JsonResult(result);
            }

            if (dto.StartTime >= dto.EndTime)
            {
                result.Message = "活动时间不正确";
                return new JsonResult(result);
            }

            //对活动类型进行判断
            if (dto.tId == default)
            {
                result.Message = "活动类型不能为空";
                return new JsonResult(result);
            }

            //判断球馆进行赋值
            if (dto.vId == default)
            {
                string? venueIdClaim = User.FindFirst("VenueId").Value;
                Guid.TryParse(venueIdClaim, out Guid venueId);

                if (venueId == default)
                {
                    result.Message = "活动所属球馆为空";
                    return new JsonResult(result);
                }
                else dto.vId = venueId;
            }

            // 映射DTO到实体
            var activity = new Activities
            {
                VenueID = dto.vId ?? Guid.Empty,
                TypeId = dto.tId,
                Title = dto.Title,
                Description = dto.Description,
                MaxNumber = dto.MaxNumber,
                StartTime = dto.StartTime,
                EndTime = dto.EndTime,
                Status =1,//默认已发布如果后续需要修改就修改
                Image = dto.Image,
                Price = dto.Price,
                DisplayDate = dto.DisplayDate,
                CreatedAt = DateTime.Now,
                UpdateAt = DateTime.Now,
                IsDeleted = false,
                Deadline = dto.Deadline,
                IsLadyDiscountEnabled = dto.IsLadyDiscountEnabled,
                LadyDiscountType = dto.LadyDiscountType,
                LadyDiscountValue = dto.LadyDiscountValue,
                PriceType = dto.PriceType,
                DepositAmount = dto.DepositAmount
            };

            // 调用服务层添加方法
            var addResult = await _activitiesServer.AddAsync(activity);

            if (addResult > 0)
            {
                result.Success = true;
                result.Message = "活动添加成功";
                // 如果需要返回数据，可以在这里添加
            }
            else
            {
                result.Message = "活动添加失败";
            }

            return new JsonResult(result);
        }

        /// <summary>
        /// 更新活动信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<JsonResult> UpdateActivity([FromBody] ActivitiesDTO dto)
        {
            var result = new ApiResult
            {
                Success = false
            };

            if (dto.StartTime >= dto.EndTime)
            {
                result.Message = "活动时间不正确";
                return new JsonResult(result);
            }

            // 检查活动是否存在
            var existingActivity = await _activitiesServer.QueryAsync(x => x.ActivityID.Equals(dto.aId));
            if (existingActivity == null)
            {
                result.Message = "指定的活动不存在";
                return new JsonResult(result);
            }

            // 检查活动状态，禁止编辑进行中和已结束的活动
            if (existingActivity.Status == 3) // 进行中
            {
                result.Message = "进行中的活动不允许编辑";
                return new JsonResult(result);
            }
            
            if (existingActivity.Status == 5) // 已结束
            {
                result.Message = "已结束的活动不允许编辑";
                return new JsonResult(result);
            }
            
            // 检查是否有人报名
            var memberCount = await _activityMembersServer.QueryCountAsync(x => x.ActivityId == existingActivity.ActivityID && x.Status == 1);
            var hasMember = memberCount > 0;
            
            // 更新实体属性(球馆不能修改防止出现错误)
            existingActivity.VenueID = existingActivity.VenueID;
            existingActivity.TypeId = dto.tId;
            existingActivity.Title = dto.Title;
            existingActivity.Description = dto.Description;
            existingActivity.Image = dto.Image;
            existingActivity.DisplayDate = dto.DisplayDate;
            existingActivity.UpdateAt = DateTime.Now;
            
            // 如果没有人报名，可以修改所有信息
            if (!hasMember)
            {
                existingActivity.MaxNumber = dto.MaxNumber;
                existingActivity.StartTime = dto.StartTime;
                existingActivity.EndTime = dto.EndTime;
                existingActivity.Status = dto.Status != 0 ? dto.Status : existingActivity.Status;
                existingActivity.Price = dto.Price;
                existingActivity.Deadline = dto.Deadline;
                existingActivity.IsLadyDiscountEnabled = dto.IsLadyDiscountEnabled;
                existingActivity.LadyDiscountType = dto.LadyDiscountType;
                existingActivity.LadyDiscountValue = dto.LadyDiscountValue;
                existingActivity.PriceType = dto.PriceType;
                existingActivity.DepositAmount = dto.DepositAmount;
            }
            else
            {
                // 有人报名了，只允许修改基础信息，价格和优惠信息不能修改
                if (existingActivity.MaxNumber != dto.MaxNumber ||
                    existingActivity.StartTime != dto.StartTime ||
                    existingActivity.EndTime != dto.EndTime ||
                    existingActivity.Price != dto.Price ||
                    existingActivity.Deadline != dto.Deadline ||
                    existingActivity.IsLadyDiscountEnabled != dto.IsLadyDiscountEnabled ||
                    existingActivity.LadyDiscountType != dto.LadyDiscountType ||
                    existingActivity.LadyDiscountValue != dto.LadyDiscountValue ||
                    existingActivity.DepositAmount != dto.DepositAmount ||
                    existingActivity.PriceType != dto.PriceType)
                {
                    result.Message = "活动已有人报名，只能修改活动基础信息（标题、描述、图片等），不能修改价格、时间、优惠等信息";
                    return new JsonResult(result);
                }
            }

            // 调用服务层更新方法
            var updateResult = await _activitiesServer.UpdateAsync(existingActivity);

            if (updateResult)
            {
                result.Success = true;
                result.Message = "活动更新成功";
                result.StatusCode = 200;
            }
            else
            {
                result.Message = "活动更新失败";
            }

            return new JsonResult(result);
        }


        /// <summary>
        /// 管理员发布活动
        /// </summary>
        /// <returns></returns>
        [HttpPatch("{id}")]
        public async Task<JsonResult> Status(int id)
        {
            var result = new ApiResult
            {
                Message = "操作成功"
            };

            string? roleId = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Role))?.Value;

            if (!(roleId == ((int)RoleEnum.Admin).ToString()) || roleId.IsNullOrWhiteSpace())
            {
                result.Message = "无操作权限";
                result.Success = false;
                return new JsonResult(result);
            }

            var data = await _activitiesServer.QueryAsync(x => x.ActivityID == id);

            if (data == null)
            {
                result.Success = false;
                result.Message = "活动不存在";
            }

            data.Status = 1;

            bool uResult = await _activitiesServer.UpdateAsync(data);

            if (!uResult)
            {
                result.Message = "操作失败";
                result.Success = false;
            }

            result.Success = true;

            return new JsonResult(result);
        }

        /// <summary>
        /// 取消活动
        /// </summary>
        /// <param name="id">活动ID</param>
        /// <param name="request">包含取消原因的请求对象</param>
        /// <returns>操作结果</returns>
        [HttpPut("cancel/{id}")]
        public async Task<JsonResult> CancelActivity(int id, [FromBody] CancelActivityRequest request)
        {
            // 获取操作人ID
            string? userIdClaim = User.FindFirst("UserId")?.Value;
            int operatorId = 0;
            int.TryParse(userIdClaim, out operatorId);

            // 验证权限（球馆管理员或系统管理员）
            string? roleId = User?.Claims?.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Role))?.Value;
            bool isAdmin = roleId == ((int)RoleEnum.Admin).ToString();
            
            string? venueIdClaim = User.FindFirst("VenueId")?.Value;
            Guid venueId = Guid.Empty;
            Guid.TryParse(venueIdClaim, out venueId);
            
            // 检查活动是否存在
            var activity = await _activitiesServer.QueryAsync(x => x.ActivityID == id);
            if (activity == null)
            {
                return new JsonResult(new ApiResult 
                { 
                    Success = false,
                    Message = "活动不存在" 
                });
            }
            
            // 验证权限（系统管理员可以取消任何活动，球馆管理员只能取消自己球馆的活动）
            if (!isAdmin && activity.VenueID != venueId)
            {
                return new JsonResult(new ApiResult 
                { 
                    Success = false,
                    Message = "无权取消此活动" 
                });
            }
            
            // 执行取消活动操作
            var result = await _activitiesServer.CancelActivityAsync(id, operatorId, request.CancelReason);
            
            return new JsonResult(result);
        }

        /// <summary>
        /// 结算AA制活动，设置实际费用并对用户进行多退少补
        /// </summary>
        /// <param name="dto">结算信息</param>
        /// <returns>结算结果</returns>
        [HttpPost("settle-aa")]
        public async Task<JsonResult> SettleAAActivity([FromBody] AAActivitySettlementDto dto)
        {
            // 获取操作人ID
            string? userIdClaim = User.FindFirst("UserId")?.Value;
            int operatorId = 0;
            int.TryParse(userIdClaim, out operatorId);

            // 获取球馆ID
            string? venueIdClaim = User.FindFirst("VenueId")?.Value;
            Guid venueId = Guid.Empty;
            Guid.TryParse(venueIdClaim, out venueId);

            if (venueId == Guid.Empty)
            {
                return new JsonResult(new ApiResult
                {
                    Success = false,
                    Message = "无法获取球馆信息"
                });
            }

            // 验证输入
            if (dto.ActivityId <= 0)
            {
                return new JsonResult(new ApiResult
                {
                    Success = false,
                    Message = "活动ID无效"
                });
            }

            if (dto.ActualCostPerPerson < 0)
            {
                return new JsonResult(new ApiResult
                {
                    Success = false,
                    Message = "每人费用不能为负数"
                });
            }

            // 执行结算操作
            var result = await _activitiesServer.SettleAAActivityAsync(dto, venueId, operatorId);
            
            return new JsonResult(result);
        }
    }
}
